/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package blacksmith.tycoon;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;

/**
 *
 * @author JEWELS
 */
public class BlacksmithTycoon extends JPanel implements Runnable {
    MouseHandling mousehand = new MouseHandling();
    private static final int PWIDTH = 600;
    private static final int PHEIGHT = 480;
    private Thread animator;
    private volatile boolean running = false;
    private volatile boolean gameOver = false;
    private int minutes, hours, days, weeks, years;
    ;
    private int timeSpeedMultiplier = 1;
    private QueuedEventHandler QEH = new QueuedEventHandler();
    public BlacksmithTycoon() {
        setBackground(Color.yellow);
        setPreferredSize(new Dimension (PWIDTH, PHEIGHT));
        setFocusable(true);
        requestFocus();
        readyForTermination();
        QEH.init();
        addMouseListener( new MouseAdapter()
        {
            public void mousePressed(MouseEvent e)
            {
                testPress(e.getX(), e.getY());
            }

            private void testPress(int x, int y) {
                if (!gameOver)
                {
                    mousehand.checkImportance(x,y);
                }
            }
        });
        i = 0;
    }
    
    public void addNotify()
    {
        super.addNotify();
        startGame();
    }
    
    private void startGame()
    {//thread init
        if (animator == null || !running)
        {
            animator = new Thread(this);
            animator.start();
        }
    }
    
    public void stopGame()
    {
        running = false;
    }
    
    public void run()
    {
        long beforeTime, timeDiff, sleepTime;
        beforeTime = System.currentTimeMillis();
        running = true;
        while(running) {
            gameUpdate();
            gameRender();
            paintScreen();
            timeDiff = System.currentTimeMillis();
            sleepTime = 20 - timeDiff;
            if (sleepTime <= 0)
                sleepTime = 5;
            try {
                Thread.sleep(20);
            }
            catch (InterruptedException ex) {}
            beforeTime = System.currentTimeMillis();
        }
        System.exit(0);
    }
    
    public static void main(String[] args) {
        BlacksmithTycoon game = new BlacksmithTycoon();
        game.addNotify();
    }
    private int i;
    private void gameUpdate()
    {
        if (!gameOver) //TODO: Add update status
        {
            minutes += .3 * timeSpeedMultiplier;
            if (minutes == 60){
                hours++; minutes = 0;}
            if (hours == 24) {
                days++; hours = 0;
                }
            if ((years % 4) != 0) { // first second and third years are normal (365 days)
                if (days == 365) {
                    days = 0; years++; }
            }
            if ((years % 4) == 0) {
                if (days == 366) {
                    days = 0; years++; }
            }
            int[] dateArray = {days, years};
            int[] timeArray = {minutes, hours};
            QEH.checkQueuedEvents(dateArray, timeArray);
            // TODO: update time texts
         }
    }
    
    
    private Graphics dbg;
    private Image dbImage;
    private int errorCount;
    private void gameRender() {
        if (dbImage == null) {
            dbImage = createImage(PWIDTH, PHEIGHT);
            if (dbImage == null)
            {
                System.out.println("Skip in animation thread - (" + (errorCount + 1) + ") skips");
                errorCount++;
                return;
            }
        }
        else dbg = dbImage.getGraphics();
        dbg.setColor(Color.white);
        dbg.fillRect(0,0,PWIDTH,PHEIGHT);
        
        if (gameOver){
            gameOverMessage(dbg);
        }
    }
    
    private void gameOverMessage(Graphics g)
    {
        //g.drawString(msg, x, y);
    }

    private void readyForTermination() {
        addKeyListener( new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e)
            {
                int keyCode = e.getKeyCode();
                if ((keyCode == KeyEvent.VK_F4) && e.isAltDown())
                {
                    running = false;
                }
            }
        });
    }

    private void paintScreen() {
        Graphics g;
        try {
            g = this.getGraphics();
            if ((g != null) && dbImage == null){
                g.drawImage(dbImage, 0, 0, null);
            }
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }
        catch (Exception e) {
            System.out.println("Graphical context error: " + e ); }
    }
}
